Skip to content

Micro-optimization: replace nested list comprehension in qsim_circuit.py#1030

Draft
mhucka wants to merge 2 commits intoquantumlib:mainfrom
mhucka:perf-matrix-gate-loop-7470006869823439752
Draft

Micro-optimization: replace nested list comprehension in qsim_circuit.py#1030
mhucka wants to merge 2 commits intoquantumlib:mainfrom
mhucka:perf-matrix-gate-loop-7470006869823439752

Conversation

@mhucka
Copy link
Copy Markdown
Collaborator

@mhucka mhucka commented Mar 30, 2026

The original code used a nested list comprehension [val for i in list(cirq.unitary(qsim_gate).flat) for val in [i.real, i.imag]], which created multiple temporary lists. We can avoid this by using some NumPy functionality, specifically the ravel() operation and NumPy views. This reinterprets the complex number array as a float array with interleaved real and imaginary parts, which is what the original list comprehension did.

…conversion

The original code used a nested list comprehension `[val for i in list(cirq.unitary(qsim_gate).flat) for val in [i.real, i.imag]]`, which created multiple temporary lists: one for the entire flattened array and one for each complex number's real/imaginary pair.

By replacing this with an explicit `for` loop and direct `.append()` calls, we avoid these allocations. Benchmarks show a ~25% performance improvement for this conversion logic.
@github-actions github-actions bot added the Size: XS <10 lines changed label Mar 30, 2026
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request modifies the add_op_to_circuit function in qsimcirq/qsim_circuit.py to replace a nested list comprehension with an explicit loop for flattening unitary matrices into interleaved real and imaginary components. A review comment suggests a more efficient and idiomatic approach using a numpy view to perform this transformation, which aligns with the style guide's emphasis on performance and vectorization.

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@mhucka mhucka marked this pull request as draft March 30, 2026 04:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Size: XS <10 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant